import 'dart:async';
import 'dart:convert';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:share_fit/app/components/back_btn_icon.dart';
import 'package:share_fit/app/controllers/main/login/http_const.dart';
import 'package:share_fit/app/controllers/main/login/register/register_logic.dart';
import 'package:share_fit/app/controllers/space/weekly/string_util.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/tools/color_const.dart';
import 'package:share_fit/app/ute/uteped_device.dart';
import 'package:share_fit/generated/locales.g.dart';

class RegisterPage extends StatelessWidget {

  final logic = Get.put(RegisterLogic());
  final FocusNode _focusNodeName = FocusNode();
  final FocusNode _focusNodeCode = FocusNode();
  final FocusNode _focusNodePwd = FocusNode();
  final FocusNode _focusNodePwd2 = FocusNode();
  String nameValue = '';
  String codeValue = '1234';
  String pwdValue = '';
  String pwd2Value = '';

  late Timer timer;
  int _timeCount = 60;
  bool isDownTimer = false;

  bool toMainPage = false;

  @override
  Widget build(BuildContext context) {
    logic.setCodeText(LocaleKeys.login_obtain_code.ts);
    _focusNodeName.addListener(() {
      logic.setNameFocus(_focusNodeName.hasFocus);
    });
    _focusNodeCode.addListener(() {
      logic.setCodeFocus(_focusNodeCode.hasFocus);
    });
    _focusNodePwd.addListener(() {
      logic.setPwdFocus(_focusNodePwd.hasFocus);
    });
    _focusNodePwd2.addListener(() {
      logic.setPwd2Focus(_focusNodePwd2.hasFocus);
    });

    if(Get.arguments!=null) {
      Map<String, dynamic> params = Get.arguments;
      if(params.containsKey('toMainPage')) {
        toMainPage = params['toMainPage'];
      }
    }

    return PopScope(
        canPop: false,
        onPopInvoked: (didPop)=>(Get.offNamed('/login', arguments: {'toMainPage': toMainPage})),
        child: Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          centerTitle: true,
          leading: BackBtnIcon(onTap: () {
            Get.offNamed('/login', arguments: {'toMainPage': toMainPage});
          }),
        ),
        body: Container(
          padding: EdgeInsets.only(top: 168.h),
          child: Column(
            children: [
              Text(LocaleKeys.login_register.ts, style: TextStyle(fontSize: 70.sp, color: Color(0xFF222222))),
              _getUsernameInput(),
              // _getInputCode(context),
              _getPasswordInput(),
              _getPassword2Input(),
              Container(
                margin: EdgeInsets.fromLTRB(42.w, 34.h, 42.w, 0),
                child: Text(LocaleKeys.reset_password_tips.ts, style: TextStyle(fontSize: 38.sp, color: ColorConst.secondaryFontColor)),
              ),
              Container(
                height: 136.h,
                width: 1.sw,
                margin: EdgeInsets.fromLTRB(42.w, 155.h, 42.w, 0),
                child: ElevatedButton(
                  onPressed: () {
                    if(nameValue.isEmpty) {
                      logic.showTips('', LocaleKeys.login_input_phone_email.ts);
                      return;
                    }
                    if(!HttpConst.email(nameValue)) {
                      logic.showTips('', LocaleKeys.email_error.ts);
                      return;
                    }

                    // if(codeValue.isEmpty) {
                    //   logic.showTips('', LocaleKeys.check_code.ts);
                    //   return;
                    // }

                    if(pwdValue.isEmpty || pwd2Value.isEmpty) {
                      logic.showTips('', LocaleKeys.login_input_password.ts);
                      return;
                    }

                    if(pwdValue!=pwd2Value) {
                      logic.showTips('', LocaleKeys.check_pwd.ts);
                      return;
                    }

                    if(!HttpConst.verifyPassword(pwdValue)) {
                      logic.showTips('', LocaleKeys.reset_password_tips.ts);
                      return;
                    }

                    if(!logic.state.isBottomSelected) {
                      logic.showTips('', LocaleKeys.check_bottom_protocol.ts);
                      return;
                    }

                    logic.showLoading();
                    logic.regist(nameValue, codeValue, pwdValue).then((value){
                      logic.cancelLoading();
                      if(value=='') {
                        logic.showTips('', LocaleKeys.network_error.ts);
                        return;
                      }
                      Map map = jsonDecode('$value');
                      if(map['errorCode']==0) {
                        UTEPedDevice.instance.getDeviceId().then((value) {
                          logic.showLoading();
                          logic.tokens(value, nameValue, 'password', pwdValue, '', '', 0)
                              .then((value){
                            logic.cancelLoading();
                            logic.showTips('', LocaleKeys.registered_successful.ts);
                            Get.offNamed('/login/register/info', arguments: {'toMainPage': toMainPage});
                            // showToast(context, '${map['message']}', onDismiss: ()=>Get.offNamed('/login/register/info'));
                          });
                        });
                      } else {
                        logic.cancelLoading();
                        logic.showTips('', HttpConst.getCodeToString(map['errorCode']));
                      }
                    });
                  },
                  style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all(ColorConst.activeColor),
                      shape: MaterialStateProperty.all(RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10)
                      ))
                  ),
                  child: Text(LocaleKeys.register_now.ts, style: TextStyle(fontSize: 48.sp, color: Colors.white, ),),
                ),),
              Spacer(),
              GestureDetector(
                onTap: (){logic.setBottomChecked(!logic.state.isBottomSelected);},
                child: Container(
                  margin: EdgeInsets.fromLTRB(42.w, 88.h, 0, 100.h),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      GetBuilder<RegisterLogic>(
                          id: 'register_bottom_selected', builder: (_){
                        return Stack(
                          children: [
                            Center(
                              child: Image.asset('assets/images/space/icon_login_unselected.png', width: 47.w, height: 47.h,),
                            ),
                            Opacity(opacity: logic.state.isBottomSelected?1:0, child: Center(
                              child: Image.asset('assets/images/space/icon_login_selected.png', width: 58.w, height: 45.h,),),)
                          ],
                        );
                      }),
                      SizedBox(width: 22.w,),
                      Expanded(child: RichText(text: TextSpan(
                          children: [
                            TextSpan(text: StringUtils.autoLineString(LocaleKeys.login_read.ts), style: TextStyle(fontSize: 42.sp, color: ColorConst.secondaryFontColor),),
                            TextSpan(text: StringUtils.autoLineString(LocaleKeys.login_agreement.ts),
                                style: TextStyle(fontSize: 42.sp, color: ColorConst.accentColor),
                                recognizer: TapGestureRecognizer()..onTap = (){
                                  Get.toNamed('/space/setting/agreement');
                                }
                            ),
                            TextSpan(text: StringUtils.autoLineString(LocaleKeys.login_and.ts), style: TextStyle(fontSize: 42.sp, color: ColorConst.secondaryFontColor),),
                            TextSpan(text: StringUtils.autoLineString(LocaleKeys.login_private.ts),
                                style: TextStyle(fontSize: 42.sp, color: ColorConst.accentColor),
                                recognizer: TapGestureRecognizer()..onTap = (){
                                  Get.toNamed('/space/setting/private');
                                }
                            ),
                          ]
                      ),)),
                    ],
                  ),
                ),
              )
            ],
          ),
        )
    ));

  }

  Widget _getUsernameInput(){
    return GetBuilder<RegisterLogic>(
        id: 'register_name_focus',
        builder: (_){
          return Container(
            margin: EdgeInsets.fromLTRB(42.w, 200.h, 42.w, 0),
            child: Column(
              children: [
                TextField(
                  maxLines: 1,
                  focusNode: _focusNodeName,
                  cursorColor: ColorConst.secondaryFontColor,
                  onChanged: (value) {
                    nameValue = value;
                  },
                  decoration: InputDecoration(
                    icon: Container(
                      alignment: Alignment.bottomCenter,
                      width: 60.w,
                      child: ColorFiltered(
                        colorFilter:ColorFilter.mode(logic.state.isFocusedName?ColorConst.accentColor:ColorConst.secondaryFontColor, BlendMode.srcATop),
                        child: Image.asset('assets/images/space/icon_login_name.png', width: 60.w, height: 60.w,),
                      ),
                      // child: Image.asset('assets/images/space/icon_login_name.png', width: 60.w, height: 60.w,),
                    ),
                    hintText: LocaleKeys.login_input_phone_email.ts,
                    hintStyle: TextStyle(color: logic.state.isFocusedName?ColorConst.accentColor:ColorConst.secondaryFontColor, fontSize: 42.sp),
                    border: InputBorder.none,
                  ),
                ),
                Divider(height: 1.h,)
              ],
            ),
          );
        });
  }

  Widget _getInputCode(BuildContext context){
    return Container(
      margin: EdgeInsets.fromLTRB(42.w, 42.h, 42.w, 0),
      child: Column(
        children: [
          Row(children: [
            GetBuilder<RegisterLogic>(
              id: 'register_code_focus',
              builder: (_){
                return SizedBox(
                  width: 0.7.sw,
                  child: TextField(
                    maxLines: 1,
                    focusNode: _focusNodeCode,
                    // enableInteractiveSelection: false,
                    cursorColor: ColorConst.secondaryFontColor,
                    onChanged: (value) {
                      codeValue = value;
                    },
                    decoration: InputDecoration(
                        icon: Container(
                          alignment: Alignment.bottomCenter,
                          width: 60.w,
                          child: ColorFiltered(
                            colorFilter:ColorFilter.mode(logic.state.isFocusedCode?ColorConst.accentColor:ColorConst.secondaryFontColor, BlendMode.srcATop),
                            child: Image.asset('assets/images/space/icon_code.png', width: 60.w, height: 60.w,),
                          ),
                        ),
                        hintText: LocaleKeys.login_input_code.ts,
                        hintStyle: TextStyle(color: logic.state.isFocusedCode?ColorConst.accentColor:ColorConst.secondaryFontColor, fontSize: 42.sp),
                        border: InputBorder.none
                    ),
                  ),
                );
              },
            ),
            GestureDetector(
              onTap: (){
                logic.showLoading();
                logic.sendVerifyCode(nameValue, "1").then((value){
                  logic.cancelLoading();
                  if(value=='') {
                    logic.showTips('', 'Error');
                    return;
                  }
                  Map map = jsonDecode('$value');
                  if(map['errorCode']==0) {
                    logic.showTips('', '${map['message']}');
                    if(!isDownTimer) {
                      startTimer();
                    }
                  } else {
                    logic.showTips('', '${map['message']}');
                  }
                });
              },
              child: Container(
                width: 250.w,
                height: 100.h,
                padding: EdgeInsets.only(bottom: 10.h),
                alignment: Alignment.bottomRight,
                child: GetBuilder<RegisterLogic>(
                  id: 'sms_code_text',
                  builder: (_){
                    return Text(logic.state.codeText, style: TextStyle(fontSize: 42.sp, color: ColorConst.accentColor),);
                  },
                ),
              ),
            ),
          ],),
          Divider(height: 1.h,)
        ],
      ),
    );
  }

  Widget _getPasswordInput(){
    return GetBuilder<RegisterLogic>(
        id: 'register_pwd_focus',
        builder: (_){
          return Container(
            margin: EdgeInsets.fromLTRB(42.w, 42.h, 42.w, 0),
            child: Column(
              children: [
                TextField(
                  maxLines: 1,
                  focusNode: _focusNodePwd,
                  // enableInteractiveSelection: false,
                  obscureText: logic.state.obscureText,
                  cursorColor: ColorConst.secondaryFontColor,
                  onChanged: (value) {
                    pwdValue = value;
                  },
                  decoration: InputDecoration(
                    icon: Container(
                      alignment: Alignment.bottomCenter,
                      width: 60.w,
                      child: ColorFiltered(
                        colorFilter:ColorFilter.mode(logic.state.isFocusedPwd?ColorConst.accentColor:ColorConst.secondaryFontColor, BlendMode.srcATop),
                        child: Image.asset('assets/images/space/icon_login_pwd.png', width: 60.w, height: 60.w,),
                      ),
                    ),
                    suffix: GestureDetector(
                      onTap: (){logic.setObscureText(!logic.state.obscureText);},
                      child: Container(
                        alignment: Alignment.bottomCenter,
                        width: 60.w,
                        child: Image.asset(!logic.state.obscureText?'assets/images/space/icon_login_pwd_visibility.png':'assets/images/space/icon_login_pwd_gone.png', width: 60.w, height: 60.w,),
                      ),
                    ),
                    hintText: LocaleKeys.reset_input_new_password.ts,
                    hintStyle: TextStyle(color: logic.state.isFocusedPwd?ColorConst.accentColor:ColorConst.secondaryFontColor, fontSize: 42.sp),
                    border: InputBorder.none,
                  ),
                ),
                Divider(height: 1.h,)
              ],
            ),
          );
        });
  }

  Widget _getPassword2Input(){
    return GetBuilder<RegisterLogic>(
        id: 'register_pwd2_focus',
        builder: (_){
          return Container(
            margin: EdgeInsets.fromLTRB(42.w, 42.h, 42.w, 0),
            child: Column(
              children: [
                TextField(
                  maxLines: 1,
                  focusNode: _focusNodePwd2,
                  // enableInteractiveSelection: false,
                  obscureText: logic.state.obscureText,
                  cursorColor: ColorConst.secondaryFontColor,
                  onChanged: (value) {
                    pwd2Value = value;
                  },
                  decoration: InputDecoration(
                    icon: Container(
                      alignment: Alignment.bottomCenter,
                      width: 60.w,
                      child: ColorFiltered(
                        colorFilter:ColorFilter.mode(logic.state.isFocusedPwd2?ColorConst.accentColor:ColorConst.secondaryFontColor, BlendMode.srcATop),
                        child: Image.asset('assets/images/space/icon_login_pwd.png', width: 60.w, height: 60.w,),
                      ),
                    ),
                    suffix: GestureDetector(
                      onTap: (){logic.setObscureText(!logic.state.obscureText);},
                      child: Container(
                        alignment: Alignment.bottomCenter,
                        width: 60.w,
                        child: Image.asset(!logic.state.obscureText?'assets/images/space/icon_login_pwd_visibility.png':'assets/images/space/icon_login_pwd_gone.png', width: 60.w, height: 60.w,),
                      ),
                    ),
                    hintText: LocaleKeys.reset_confirm_new_password.ts,
                    hintStyle: TextStyle(color: logic.state.isFocusedPwd2?ColorConst.accentColor:ColorConst.secondaryFontColor, fontSize: 42.sp),
                    border: InputBorder.none,
                  ),
                ),
                Divider(height: 1.h,)
              ],
            ),
          );
        });
  }

  void startTimer() {
    timer = Timer.periodic(const Duration(seconds: 1), (Timer timer) {
      if(_timeCount<=0) {
        isDownTimer = false;
        _timeCount = 120;
        timer.cancel();
        logic.setCodeText(LocaleKeys.login_obtain_code.ts);
      } else {
        isDownTimer = true;
        logic.setCodeText('$_timeCount ${LocaleKeys.time_unit_second.ts}');
        _timeCount -= 1;
      }
    });
  }

}